package com.example.lagou_elasticsearch_homework.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 工具类
 */
public class Util {

    /**
     * 集合中类型转换
     * @param sourceList
     * @param targetClazz
     * @param <T>
     * @param <K>
     * @return
     */
    public static  <T,K> List<K>  convertList(List<T> sourceList,Class<K> targetClazz){
        if(CollectionUtils.isEmpty(sourceList)){
            return null;
        }
        List<K> result = sourceList.stream().map(t -> {
            try {
                K k = targetClazz.newInstance();
                BeanUtils.copyProperties(t, k);
                return k;
            } catch (Exception e) {
                return null;
            }
        }).filter(k -> k != null).collect(Collectors.toList());
        return result;
    }
}
